<template>
	<view ref="scroll-bar-item" class="scroll-bar-item" @tap="itemTap">
		<slot></slot>
	</view>
</template>

<script>
export default {
	inject: ['scrollTabBar'],
	props: {
		
	},
	data() {
		return {
			index: 0,
			tabBarItemWidth: 0,
		}
	},
	methods: {
		// #ifdef APP-NVUE
		getComponentRect(ref) {
			
			const dom = uni.requireNativePlugin('dom');
			
			return new Promise(function (resolve, reject) {
				dom.getComponentRect(ref, data => {
					resolve(data);
				});
			})
		},
		// #endif
		itemTap(e) {
			
			let distance = e.currentTarget.offsetLeft - uni.getSystemInfoSync().windowWidth/2 + this.tabBarItemWidth/2;
			
			this.scrollTabBar.scrollLeft = distance<0 ? 0:distance;
			
			this.scrollTabBar.underlineOffsetLeft = e.currentTarget.offsetLeft;
		}
	},
	created() {
		this.index = this.scrollTabBar.itemIndex++;
	},
	mounted() {
		
		this.$nextTick(function () {
			//setTimeout(async () => {
				// #ifndef APP-PLUS-NVUE
				uni.createSelectorQuery().in(this).select('.scroll-bar-item').fields({size: true},data=>{
					
					this.tabBarItemWidth = data.width;
					
					if(this.index==0) this.scrollTabBar.underlineWidth = this.tabBarItemWidth;
					
				}).exec();
				// #endif
				
				// #ifdef APP-PLUS-NVUE
				
				const tabBarItemData = await this.getComponentRect(this.$refs['scroll-bar-item']);
				
				this.tabBarItemWidth = tabBarItemData.size.width;
				
				if(this.index==0) this.scrollTabBar.underlineWidth = this.tabBarItemWidth;
				
				// #endif
			//}, 10);
		})
	}
}
</script>

<style scoped>
.scroll-bar-item {
	
}
</style>